<?php

/**
 * @package site
 */

class SaleSummaryReport extends SS_Report implements PermissionProvider {
	protected $total = array();
	
	public function title() {
		return _t('SaleSummaryReport.TITLE', 'Sale Summary Report');
	}
	
	/**
	 * @param Member $member
	 * @return boolean
	 */
	public function canView($member = null) {
		if(!$member && $member !== FALSE) {
			$member = Member::currentUser();
		}
		
		$extended = $this->extendedCan(__FUNCTION__, $member);
		if($extended !== null) return $extended;

        return Permission::check('VIEW_SaleSummaryReport');
	}
	
	public function extendedCan($methodName, $member) {
		$results = $this->extend($methodName, $member);
		if($results && is_array($results)) {
			// Remove NULLs
			$results = array_filter($results, function($v) {return !is_null($v);});
			// If there are any non-NULL responses, then return the lowest one of them.
			// If any explicitly deny the permission, then we don't get access 
			if($results) return min($results);
		}
		return null;
	}
	
	public function getCMSFields() {
		$fields = new FieldList();

		if($title = $this->title()) {
			$fields->push(new LiteralField('ReportTitle', "<h3>{$title}</h3>"));
		}
		
		if($description = $this->description()) {
			$fields->push(new LiteralField('ReportDescription', "<p>" . $description . "</p>"));
		}
			
		// Add search fields is available
		if($this->hasMethod('parameterFields') && $parameterFields = $this->parameterFields()) {
			foreach($parameterFields as $field) {
				// Namespace fields for easier handling in form submissions
				$field->setName(sprintf('filters[%s]', $field->getName()));
				$field->addExtraClass('no-change-track'); // ignore in changetracker
				$fields->push($field);
			}

			// Add a search button
			$fields->push(new FormAction('updatereport', _t('GridField.Filter')));
		}
		
		$fields->push($this->getReportField());
		
		$fields->insertBefore(NumericField_Readonly::create('TotalSalesAmount', _t('SaleSummaryReport.TOTAL_SALES_AMOUNT', 'Total Sales Amount'), DBField::create_field('Currency', $this->total['Price'])->Nice()), 'Report');
		$fields->insertBefore(NumericField_Readonly::create('TotalSalesBV', _t('SaleSummaryReport.TOTAL_SALES_BV', 'Total Sales BV'), DBField::create_field('Int', $this->total['BV'])->Formatted()), 'Report');

		$this->extend('updateCMSFields', $fields);
		
		return $fields;
	}
	
	public function sourceRecords($params, $sort, $limit) {
		if($sort) {
			$parts = explode(' ', $sort);
			$field = $parts[0];
			$direction = $parts[1];
			
			if($field == 'Name') {
			    $sort = 'FirstName ' . $direction;
			}
		}

		$ret = OrderPackage::get()->sort($sort)->limit($limit);

		if(isset($params['Submit']) && $params['Submit']){
	        if(isset($params['StartDate']) && $params['StartDate']){
	        	$ret = $ret->filter('Created:GreaterThanOrEqual', DBField::create_field('Date', $params['StartDate'])->URLDate() . '00:00:00');
	        }
		}
		else{
			$ret = $ret->filter('Created:GreaterThanOrEqual', date('Y-m-01 00:00:00'));
		}
		
		if(isset($params['Submit']) && $params['Submit']){
			if(isset($params['EndDate']) && $params['EndDate']){
	        	$ret = $ret->filter('Created:LessThanOrEqual', DBField::create_field('Date', $params['EndDate'])->URLDate() . '23:59:59');
	        }
		}
		else{
			$ret = $ret->filter('Created:LessThanOrEqual', date('Y-m-t 23:59:59'));
		}
        
        if(isset($params['Username']) && $params['Username']){
        	$ret = $ret->filter('Member.Username:PartialMatch', $params['Username']);
        }
        
        if(isset($params['ID']) && $params['ID']){
        	$ret = $ret->filter('ID', $params['ID']);
        }

		if(isset($params['Status']) && $params['Status']){
        	$ret = $ret->filter('Status', $params['Status']);
        }
		
		if(isset($params['PaymentMode']) && $params['PaymentMode']){
			if($params['PaymentMode'] == 'with_payment'){
        		$ret = $ret->filter('PaymentReceiptID:GreaterThan', 0);
			}
			else{
				$ret = $ret->filter('PaymentReceiptID', 0);
			}
        }
		
		$this->total = array('BV' => 0, 'Price' => 0, 'Sales' => 0);
		foreach($ret as $item){
			$this->total['BV'] += $item->BV;
			$this->total['Price'] += $item->Price;
			$this->total['Sales'] += 1;
		}

		return $ret;
	}

	public function columns() {
		$fields = array(
			'Created' => array(
				'title' => _t('SaleSummaryReport.ORDER_DATE', 'Order Date'),
                'casting' => 'Datetime->Nice'
			),
			'Member.Username' => array(
				'title' => _t('SaleSummaryReport.USERNAME', 'Username')
			),
			'Member.Name' => array(
				'title' => _t('SaleSummaryReport.NAME', 'Name')
			),
			'BV' => array(
                'title' => _t('SaleSummaryReport.BV', 'BV'),
                'casting' => 'Int->Formatted'
            ),
            'Price' => array(
                'title' => _t('SaleSummaryReport.PRICE', 'Price'),
                'casting' => 'Double->Nice'
            ),
            'Status' => array(
                'title' => _t('SaleSummaryReport.STATUS', 'Status')
            ),
            'Print' => array(
				'title' => '',
				'formatting' => function($value, $item) {
					if($item->canPrint()){
						$link = sprintf('%s?id=%s', $this->getLink('doPrint'), $item->ID);
				    	return sprintf('<a href="%s" target="_blank" data-print-link="%s" class="print-link">%s</a>', $link, $link, _t('SaleSummaryReport.PRINT', 'Print'));
				    }
                }
			)
		);
		
		return $fields;
	}
	
	public function parameterFields() {
		return FieldList::create(
            FieldGroup::create(
            	DateField::create('filters[StartDate]', '', date('Y-m-01'))->addExtraClass('no-change-track'),
				DateField::create('filters[EndDate]', '', date('Y-m-t'))->addExtraClass('no-change-track')
			)->setTitle(_t('SaleSummaryReport.ORDER_DATE', 'Order Date')),
			UsernameField::create('Username', _t('SaleSummaryReport.USERNAME', 'Username')),
			NumericField::create('ID', _t('SaleSummaryReport.ORDER_ID', 'Order ID')),
			DropdownField::create('Status', _t('SaleSummaryReport.STATUS', 'Status'), singleton('OrderPackage')->dbObject('Status')->enumValues())->setEmptyString(_t('SaleSummaryReport.ALL', 'All')),
			DropdownField::create('PaymentMode', _t('SaleSummaryReport.PAYMENT_TYPE', 'Payment Type'), array('with_payment' => _t('SaleSummaryReport.WITH_PAYMENT', 'With Payment'), 'without_payment' => _t('SaleSummaryReport.WITHOUT_PAYMENT', 'Without Payment')))->setEmptyString(_t('SaleSummaryReport.ALL', 'All')),
			HiddenField::create('Submit', 'Submit', 1)
		);
	}

	public function providePermissions() {
        return array(
            'VIEW_SaleSummaryReport' => array(
                'name' => _t('SaleSummaryReport.PERMISSION_VIEW', 'Allow view access right ({title})', '', array('title' => $this->title())),
                'category' => _t('SaleSummaryReport.PERMISSIONS_CATEGORY', 'Report')
            )
        );
    }
}
